using AdmissionQA.Application.Common;
using AdmissionQA.Application.Dtos.Issue;
using AdmissionQA.Application.ServiceInterfaces;
using AdmissionQA.Domain.Entities;
using AdmissionQA.Domain.Repositorys;
using Microsoft.Extensions.Logging;

namespace AdmissionQA.Application.Services;

/// <summary>
/// 常见问题服务实现
/// </summary>
public class IssueServices(IRepository<Issue> repository, ILogger<IssueServices> logger, ITextEmbeddingService embeddingService)
    : IIssueServices
{
    private readonly IRepository<Issue> _repository = repository;
    private readonly ILogger<IssueServices> _logger = logger;
    private readonly ITextEmbeddingService _embeddingService = embeddingService;

    /// <summary>
    /// 批量创建常见问题
    /// </summary>
    /// <param name="issues">常见问题列表</param>
    /// <returns>创建结果</returns>
    public async Task<Result<string>> CreateIssuesAsync(IssuesDto issues)
    {
        var issuesToCreate = issues
            .Issues.Select(item => Issue.CreateIssue(item.Question, item.Answer))
            .Where(item => item != null)
            .Select(item => item!)
            .ToList();

        if (issuesToCreate.Count == 0)
        {
            _logger.LogWarning("批量创建常见问题失败：没有有效的问题");
            return Result<string>.Fail("没有有效的常见问题可以创建");
        }

        await _repository.CreateRangeAsync(issuesToCreate);
        _logger.LogInformation("批量创建常见问题成功，数量：{Count}", issuesToCreate.Count);
        return Result<string>.Success("创建成功");
    }

    /// <summary>
    /// 创建常见问题
    /// </summary>
    /// <param name="issue">常见问题</param>
    /// <returns>创建结果</returns>
    public async Task<Result<string>> CreateIssueAsync(IssueDto issue)
    {
        var entity = Issue.CreateIssue(issue.Question, issue.Answer);
        if (entity == null)
        {
            _logger.LogWarning("创建常见问题失败，参数：{@Issue}", issue);
            return Result<string>.Fail("创建常见问题失败");
        }
        var content = issue.Question + " " + issue.Answer + " " + (issue.Description ?? "");
        entity.Embedding = _embeddingService.GetVector(content);
        await _repository.CreateAsync(entity);
        _logger.LogInformation("创建常见问题成功，问题：{Question}", issue.Question);
        return Result<string>.Success("创建成功");
    }

    /// <summary>
    /// 批量删除常见问题
    /// </summary>
    /// <param name="ids">常见问题ID列表</param>
    /// <returns>删除结果</returns>
    public async Task<Result<string>> DeleteIssuesAsync(IEnumerable<Guid> ids)
    {
        // 并行获取所有常见问题
        var tasks = ids.Select(id => _repository.GetByIdAsync(id));
        var issues = await Task.WhenAll(tasks);

        // 过滤掉 null 值并转换为非空类型
        var validIssues = issues.OfType<Issue>().ToList();

        // 检查是否有有效的常见问题
        if (validIssues.Count == 0)
        {
            _logger.LogWarning("批量删除常见问题失败：未找到任何问题，ids={@Ids}", ids);
            return Result<string>.Fail("没有找到常见问题");
        }

        // 调用 Delete 方法标记为删除
        foreach (var issue in validIssues)
        {
            if (!issue.Delete())
            {
                _logger.LogWarning("批量删除常见问题时，问题已被删除，id={Id}", issue.Id);
                return Result<string>.Fail($"常见问题 {issue.Id} 已经被删除");
            }
        }

        // 更新所有有效的常见问题
        await _repository.UpdateRangeAsync(validIssues);
        _logger.LogInformation("批量删除常见问题成功，数量：{Count}", validIssues.Count);

        return Result<string>.Success("删除成功");
    }

    /// <summary>
    /// 删除常见问题
    /// </summary>
    /// <param name="id">常见问题ID</param>
    /// <returns>删除结果</returns>
    public async Task<Result<string>> DeleteIssueAsync(Guid id)
    {
        var issue = await _repository.GetByIdAsync(id);
        if (issue == null)
        {
            _logger.LogWarning("删除常见问题失败：未找到问题，id={Id}", id);
            return Result<string>.Fail("没有找到常见问题");
        }
        if (!issue.Delete())
        {
            _logger.LogWarning("删除常见问题失败：问题已被删除，id={Id}", id);
            return Result<string>.Fail("常见问题已经被删除");
        }
        await _repository.UpdateAsync(issue);
        _logger.LogInformation("删除常见问题成功，id={Id}", id);
        return Result<string>.Success("删除成功");
    }

    /// <summary>
    /// 根据ID获取常见问题
    /// </summary>
    /// <param name="id">常见问题ID</param>
    /// <returns>常见问题</returns>
    public async Task<Result<Issue>> GetIssueByIdAsync(Guid id)
    {
        var issue = await _repository.GetByIdAsync(id);
        if (issue == null)
        {
            return Result<Issue>.Fail("没有找到常见问题");
        }
        return Result<Issue>.Success(issue);
    }

    /// <summary>
    /// 获取常见问题数量
    /// </summary>
    /// <returns>常见问题数量</returns>
    public async Task<int> GetIssueCountAsync()
    {
        return await _repository.GetCountAsync();
    }

    /// <summary>
    /// 获取所有常见问题
    /// </summary>
    /// <returns>常见问题列表</returns>
    public async Task<Result<IEnumerable<Issue>>> GetAllIssuesAsync()
    {
        var issues = await _repository.GetAllAsync();
        return Result<IEnumerable<Issue>>.Success(issues);
    }

    /// <summary>
    /// 分页获取常见问题
    /// </summary>
    /// <param name="pageIndex">页码</param>
    /// <param name="pageSize">页大小</param>
    /// <returns>分页结果</returns>
    public async Task<Result<IEnumerable<Issue>>> GetPagedIssuesAsync(
        int pageIndex = 0,
        int pageSize = 10
    )
    {
        var issues = await _repository.GetPagedAsync(pageIndex, pageSize);
        return Result<IEnumerable<Issue>>.Success(issues);
    }

    /// <summary>
    /// 根据问题内容搜索常见问题
    /// </summary>
    /// <param name="question">问题内容</param>
    /// <returns>匹配的常见问题列表</returns>
    public async Task<Result<IEnumerable<Issue>>> SearchIssuesByQuestionAsync(string question)
    {
        var issues = await _repository.GetListConditionAsync(item =>
            item.Question.Contains(question)
        );
        return Result<IEnumerable<Issue>>.Success(issues);
    }

    /// <summary>
    /// 更新常见问题
    /// </summary>
    /// <param name="id">常见问题ID</param>
    /// <param name="issue">常见问题</param>
    public async Task<Result<string>> UpdateIssueAsync(Guid id, IssueDto issue)
    {
        var entity = await _repository.GetByIdAsync(id);
        if (entity == null)
        {
            _logger.LogWarning("更新常见问题失败：未找到问题，id={Id}", id);
            return Result<string>.Fail("没有找到常见问题");
        }
        entity.UpdateIssue(issue.Question, issue.Answer, issue.Description);
        var content = issue.Question + " " + issue.Answer + " " + (issue.Description ?? "");
        entity.Embedding = _embeddingService.GetVector(content);
        await _repository.UpdateAsync(entity);
        _logger.LogInformation("更新常见问题成功，id={Id}", id);
        return Result<string>.Success("更新成功");
    }

    public async Task<Result<IEnumerable<Issue>>> SearchIssuesByEmbeddingAsync(string text, int topK = 5)
    {
        var queryEmbedding = _embeddingService.GetVector(text);
        var all = await _repository.GetAllAsync();
        var withScore = all.Where(x => x.Embedding != null)
            .Select(x => new { Entity = x, Score = CosineSimilarity(queryEmbedding, x.Embedding!) })
            .OrderByDescending(x => x.Score)
            .Take(topK)
            .Select(x => x.Entity)
            .ToList();
        return Result<IEnumerable<Issue>>.Success(withScore);
    }
    private static float CosineSimilarity(float[] v1, float[] v2)
    {
        if (v1 == null || v2 == null || v1.Length != v2.Length) return 0f;
        float dot = 0, norm1 = 0, norm2 = 0;
        for (int i = 0; i < v1.Length; i++)
        {
            dot += v1[i] * v2[i];
            norm1 += v1[i] * v1[i];
            norm2 += v2[i] * v2[i];
        }
        if (norm1 == 0 || norm2 == 0) return 0f;
        return dot / (float)(Math.Sqrt(norm1) * Math.Sqrt(norm2));
    }
}
